<template>
  <div class="flexContent">
    <div class="searchBox">
      <!-- 供应商出库报表 -->
      <el-form class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品类型">
                  <el-select v-model="type" filterable @change="changeType" popper-class="eloption" style="width: 95%;"
                    placeholder="请选择">
                    <el-option value="0" label="标品" />
                    <el-option value="1" label="非标品" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="供应商">
                  <el-select v-model="sForm.supplierId" @click.native="getSCMList" filterable clearable
                    popper-class="eloption" style="width: 95%;" placeholder="请选择">
                    <el-option v-for="shop in firstSupplierList" :key="shop.id" :value="shop.id" :label="shop.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="10" :xl="6">
                <el-form-item label="日期">
                  <el-date-picker v-model="date" clearable type="daterange" unlink-panels range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 95%;" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" v-has="'goods_add'" @click="exportFn">导出</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="supplierName" title="供应商名称"
            :min-width="elTableAdaptationWidth('supplierName', scmOutBoundList)" />
          <vxe-column field="commodityName" title="商品名称"
            :min-width="elTableAdaptationWidth('commodityName', scmOutBoundList)" />
          <vxe-column field="firstCode" v-if="type == '0'" title="商品条码"
            :min-width="elTableAdaptationWidth('firstCode', scmOutBoundList)" />
          <vxe-column field="categoryName" v-if="type == '1'" title="商品分类"
            :min-width="elTableAdaptationWidth('categoryName', scmOutBoundList)" />
          <vxe-column field="outCount" v-if="type == '0'" title="商品累计出库量" min-width="150" />
          <vxe-column field="outWeight" v-if="type == '1'" title="商品累计出库量(KG)" min-width="150" />
          <vxe-column field="outMoney" title="累计出库金额" width="150" />
          <vxe-column v-if="$showFn(['outBound_details'])" fixed="right" width="100" title="操作">
            <template v-slot="{ row }">
              <el-button type="text" style="margin-right: 5px" @click.stop="detail(row)"
                v-has="'outBound_details'">详情</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,-> , sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getSupplierProductOutReport, getSupplierNonstandardProductOutReport, exportSupplierNonstandardProductOutReport, exportSupplierProductOutReport, getAllSupplier } from "@/api/report";
export default {
  name: "initialReport",
  data() {
    return {
      sForm: {
        supplierId: '',
        maxDate: '',
        minDate: '',
      },
      type: '0',
      date: '',
      scmOutBoundList: [],
      firstSupplierList: [],
      isSearch: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      allDataArr: [],
    };
  },
  created() {
    this.getSupplierProductOutReport();
    this.getSCMList();
  },
  activated() {
    this.isSearch = true
    this.getSupplierProductOutReport();
    this.getSCMList();
  },
  methods: {
    async getSupplierProductOutReport() {
      if (!this.isSearch) {
        this.sForm = {
          supplierId: '',
          maxDate: '',
          minDate: ''
        }
      }
      const res = await getSupplierProductOutReport({
        ...this.page,
        ...this.sForm
      });
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        this.scmOutBoundList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        console.log("shopList", this.scmOutBoundList);
        const $table = this.$refs.xTable1
        $table.loadData(this.scmOutBoundList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getSupplierNonstandardProductOutReport() {
      if (!this.isSearch) {
        this.sForm = {
          supplierId: '',
          maxDate: '',
          minDate: '',
        }
      }
      const res = await getSupplierNonstandardProductOutReport({
        ...this.page,
        ...this.sForm
      });
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        this.scmOutBoundList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        console.log("shopList", this.scmOutBoundList);
        const $table = this.$refs.xTable1
        $table.loadData(this.scmOutBoundList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async getSCMList() {
      const res = await getAllSupplier();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data;
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      if (this.type == '0') {
        this.getSupplierProductOutReport();
      } else {
        this.getSupplierNonstandardProductOutReport();
      }
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      if (this.type == '0') {
        this.getSupplierProductOutReport();
      } else {
        this.getSupplierNonstandardProductOutReport();
      }
    },
    changeType() {
      this.date = []
      this.sForm = {
        supplierId: '',
        maxDate: '',
        minDate: '',
      }
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      if (this.type == '0') {
        this.getSupplierProductOutReport();
      } else {
        this.getSupplierNonstandardProductOutReport();
      }
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.sForm.maxDate = this.date.length > 0 ? this.date[1] : '';
      this.sForm.minDate = this.date.length > 0 ? this.date[0] : ''
      this.isSearch = true;
      if (this.type == '0') {
        this.getSupplierProductOutReport();
      } else {
        this.getSupplierNonstandardProductOutReport();
      }
    },
    resetFn() {
      this.date = []
      this.sForm = {
        supplierId: '',
        maxDate: '',
        minDate: '',
      }
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      if (this.type == '0') {
        this.getSupplierProductOutReport();
      } else {
        this.getSupplierNonstandardProductOutReport();
      }
    },
    async exportFn() {
      this.$confirm('确认导出数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (!this.isSearch) {
          this.sForm = {
            supplierId: '',
            maxDate: '',
            minDate: '',
          }
        }
        let response = {}
        if (this.type == '0') {
          response = await exportSupplierProductOutReport({
            ...this.sForm
          })
        } else {
          response = await exportSupplierNonstandardProductOutReport({
            ...this.sForm
          })
        }
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    },
    detail(row) {
      if (!this.isSearch) {
        this.sForm = {
          supplierId: '',
          maxDate: '',
          minDate: '',
        }
      }
      this.$router.push({
        path: '/reportInfo/scmOutRoundReportDetail',
        query: {
          supplierId: row.supplierId,
          minDate: this.sForm.minDate,
          maxDate: this.sForm.maxDate,
          type: this.type,
          commodityId: row.commodityId
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.txtBox {
  padding-left: 20px;
  margin-bottom: 30px;

}

.btnBOX {
  text-align: center;
}
</style>
